import { File } from '@/api/interface/file';
import { BasicForm } from '@/components/ProForm/interface';
import { ProTableValue } from '@/interface/public';

export const useFile = (addFileForm: BasicForm<File.ReqUpload>, fileRef: ProTableValue) => {
  // const globalStore = useGlobalStore();
  let fileObj = ref({
    uploadingData: {
      remark: ''
    },
    fileList: [],
    headers: {
      TOKEN: useUserStore().token
    },
    maxSize: 10485760,
    acceptSuffix: '.jpeg,.png,.jpg,.txt,.doc,.docx,.xls,.xlsx,.pdf',
    imgSuffix: ['.jpeg', '.png', '.jpg']
  });

  const getSuffix = (fileName: string) => {
    const key = fileName.lastIndexOf('.');
    const nameLength = fileName.length;
    const fileSuffix = fileName.substring(key, nameLength);
    return fileSuffix;
  };

  /**
   * @description: 是否是图片格式
   * @param {*} row
   * @return {*}
   */
  const isImg = (row: any) => {
    const { fileSuffix: f } = row || {};
    if (!f) return false;
    const fileSuffix = getSuffix(f);

    return fileObj.value.imgSuffix.includes(fileSuffix);
  };

  const onChange = (file: any, fileList: any) => {
    fileObj.value.fileList = fileList;
    if (fileList?.length) {
      const { name } = fileList[0];
      const suffix = getSuffix(name);

      const key = name.indexOf('.');
      const _name = name.substring(0, key);

      Object.assign(addFileForm.form, {
        fileSuffix: suffix,
        fileName: !addFileForm.form.fileName ? _name : addFileForm.form.fileName
      });
    }
  };
  const onExceed = () => {
    elMessage('一次只能上传一个文件', 'warning');
  };
  const onSuccess = () => {
    fileRef.value?.search();
    addFileForm.visible = false;
    elMessage();
  };
  // 上传前
  const fileBeforeUpload = (file: any) => {
    const { name, size } = file || {};
    const key = name.lastIndexOf('.');
    const nameLength = name.length;
    // 可接受的文件类型
    const accept = fileObj.value.acceptSuffix.split(',');
    const fileSuffix = name.substring(key, nameLength);
    if (!accept.includes(fileSuffix)) {
      elMessage(`只能上传${fileObj.value.acceptSuffix}类型文件`, 'warning');
      return false;
    }

    if (size > fileObj.value.maxSize) {
      elMessage('上传数据不能大于10M', 'warning');
      return false;
    }
  };

  return { fileObj, isImg, onChange, fileBeforeUpload, onSuccess, onExceed };
};
